use ratatui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout},
    widgets::{Block, Borders},
    Terminal,
};
use tui_textarea::{Input, Key, TextArea};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use ratatui::style::{Color, Style};


pub struct PrForm {
    pub title: TextArea<'static>,
    pub head: TextArea<'static>,
    pub base: TextArea<'static>,
    pub body: TextArea<'static>,
    pub current: usize,
}

impl PrForm {
    pub fn new() -> Self {
        let mut form = PrForm {
            title: TextArea::default(),
            head: TextArea::default(),
            base: TextArea::default(),
            body: TextArea::default(),
            current: 0,
        };

        form.title.set_block(Block::default().title("PR 标题").borders(Borders::ALL));
        form.head.set_block(Block::default().title("源分支 (head)").borders(Borders::ALL));
        form.base.set_block(Block::default().title("目标分支 (base)").borders(Borders::ALL));
        form.body.set_block(Block::default().title("描述 (body)").borders(Borders::ALL));

        form
    }

    pub fn handle_event(&mut self, event: Event) -> bool {
        if let Event::Key(key_event) = event {
            match key_event.code {
                KeyCode::Esc => return true,
                KeyCode::Tab => {
                    self.current = (self.current + 1) % 4;
                    return false;
                }
                KeyCode::BackTab => {
                    self.current = (self.current + 3) % 4;
                    return false;
                }
                _ => {}
            }

            if let Some(input) = convert_key_event(key_event) {
                self.current_field_mut().input(input);
            }
        }
        false
    }

    fn current_field_mut(&mut self) -> &mut TextArea<'static> {
        match self.current {
            0 => &mut self.title,
            1 => &mut self.head,
            2 => &mut self.base,
            _ => &mut self.body,
        }
    }

    pub fn render<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<(), std::io::Error> {
        terminal.draw(|f| {
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .margin(2)
                .constraints([
                    Constraint::Length(3),
                    Constraint::Length(3),
                    Constraint::Length(3),
                    Constraint::Min(5),
                ])
                .split(f.area());
    
            let highlight = Style::default().fg(Color::LightBlue);
            let normal = Style::default().fg(Color::DarkGray);
    
            let blocks = [
                ("PR 标题", &mut self.title, 0),
                ("源分支 (head)", &mut self.head, 1),
                ("目标分支 (base)", &mut self.base, 2),
                ("描述 (body)", &mut self.body, 3),
            ];
    
            for (label, field, index) in blocks {
                let block = Block::default()
                    .title(label)
                    .borders(Borders::ALL)
                    .border_style(if self.current == index { highlight } else { normal });
            
                field.set_block(block);
                field.set_cursor_line_style(Style::default().fg(Color::White));
                field.set_cursor_style(if self.current == index {
                    Style::default().fg(Color::White)
                } else {
                    Style::default().fg(Color::Reset)
                });
            
                // ❗ 改这里：不可传 &mut
                f.render_widget(&*field, chunks[index]);
            }
        })?;
        Ok(())
    }
    
}

fn convert_key_event(ev: KeyEvent) -> Option<Input> {
    let key = match ev.code {
        KeyCode::Char(c) => Key::Char(c),
        KeyCode::Enter => Key::Enter,
        KeyCode::Tab => Key::Tab,
        KeyCode::Backspace => Key::Backspace,
        KeyCode::Delete => Key::Delete,
        KeyCode::Left => Key::Left,
        KeyCode::Right => Key::Right,
        KeyCode::Up => Key::Up,
        KeyCode::Down => Key::Down,
        KeyCode::Home => Key::Home,
        KeyCode::End => Key::End,
        KeyCode::PageUp => Key::PageUp,
        KeyCode::PageDown => Key::PageDown,
        _ => return None,
    };

    Some(Input {
        key,
        ctrl: ev.modifiers.contains(KeyModifiers::CONTROL),
        alt: ev.modifiers.contains(KeyModifiers::ALT),
        shift: ev.modifiers.contains(KeyModifiers::SHIFT),
    })
}
